<template>
  <div class="community-page">
    <!-- 页签 -->
    <div class="tabs">
      <div
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab-item', { active: currentTab === index }]"
        @click="onTabClick(index)"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 社区列表 -->
    <CommunityList
      :postVos="postData"
      v-if="postData.length > 0"
      @load-more="loadMore"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import CommunityList from '@/views/home/community/CommunityList.vue'
import { searchMyPost } from '@/api/CommunityApi'

// 页签配置
const tabs = [
  { label: '我的', type: 0 },
  { label: '喜欢', type: 1 },
  { label: '收藏', type: 2 }
]

const currentTab = ref(0)       // 当前选中的页签索引
const postData = ref([])        // 社区帖子数据
const currentPage = ref(1)
const pageSize = 12
const hasMore = ref(true)

// 点击页签
const onTabClick = async (index) => {
  currentTab.value = index
  currentPage.value = 1
  postData.value = []
  await loadData(tabs[index].type)
}

// 加载数据
const loadData = async (type, append = false) => {
  try {
    const res = await searchMyPost(type, currentPage.value, pageSize)
    const newPosts = res?.data.data.postVos || []

    hasMore.value = newPosts.length === pageSize

    if (append) {
      postData.value.push(...newPosts)
    } else {
      postData.value = newPosts
    }
  } catch (error) {
    console.error('获取帖子失败', error)
  }
}

const loadMore = () => {
  if (hasMore.value) {
    currentPage.value++
    loadData(tabs[currentTab.value].type, true)
  }
}

// 初始化加载“我的”
onMounted(() => {
  loadData(tabs[currentTab.value].type)
})
</script>

<style scoped>
.community-page {
  display: flex;
  flex-direction: column;
  padding: 16px;
  background: url('@/assets/community/MyPostBg.png') no-repeat center top;
  --offset-x: 5px;
  --offset-y: 55px;
  background-position: calc(-1 * var(--offset-x, 0px)) calc(-1 * var(--offset-y, 0px));
  min-height: 100vh; /* 保证最少铺满一屏 */

}
.tabs {
  display: flex;
  gap: 0px;
  margin-top: 50px;
  margin-left: 250px;
  margin-bottom: 50px;
}

.tab-item {
  width: 170px;
  height: 43px;
  text-align: left;
  padding-left: 16px;
  line-height: 43px;
  cursor: pointer;
  font-weight: 600;
  font-size: 16px;
  color: #333333;
  background-color: #F5F0E6;
  border: 1px solid #7E4B3C;
  transition: all 0.3s;
  flex-shrink: 0;
  margin-right: -1px;
  box-sizing: border-box;
}

.tab-item.active {
  background-color: #F2D3A9;
  color: #4B2E1E;
}

</style>
